

var plantAndBreedForm = new Vue({
	el: '#plantAndBreedForm',
	data: {
		wd: '',
		jd: '',
		photos: [], //图片集合
		formtype: 0,
		uploadcount: 0, //判断结束
		fammername: '',
		fammerid: '',
		level: '',
		acqbreedid: [],
		acqplantid: [],
		scale: '',
		output: '',
		returndate: '', //预计收益日期
		ycdate: '',
		bcdate: '',
		des: '',
		plantArea: 0,
		plantAreaName: "亩",
		returnUnit: 0,
		returnUnitName: "公斤",
		delNo: 0
	},
	watch: {
		uploadcount: function(curVal, oldVal) {
			var _this = this
			var l = this.photos.length
			if(curVal != 0 && curVal == l) {
				setTimeout(function() {
					plus.nativeUI.closeWaiting();

					mui.alert("提交成功", function() {
						document.getElementById('form').reset()
						_this.photos = [],
							_this.uploadcount = 0
						_this.fammerid = ''
						_this.level = ''
						_this.acqbreedid = []
						_this.acqplantid = []
						_this.scale = ''
						_this.output = ''
						_this.returndate = ''
						_this.ycdate = ''
						_this.bcdate = ''
						_this.des = ''
						var old_back = mui.back;
						old_back();
					})
				}, 2000);

			}
		},
		　　　　　　
	/*	formtype: function(curVal, oldVal) {
			document.getElementById('form').reset()
			this.photos = [],
				this.uploadcount = 0
			this.level = ''
			this.acqbreedid = []
			this.acqplantid = []
			this.scale = ''
			this.output = ''
			this.returndate = ''
			this.returndate = ''
			this.ycdate = ''
			this.bcdate = ''
			this.des = ''
		}　　*/
	},
	mounted: function() {
		this.pushData()
	},
	methods: {
		pushData:function(){
			var id = localStorage.localid
			var _this = this
			db.transaction(function (tx) {
   			tx.executeSql('SELECT * FROM info where id='+id, [], function (tx, results) {
		   	   //初始化赋值
		   	        _this.formtype = results.rows.item(0).formtype;
			         _this.des = results.rows.item(0).des;
			         _this.jd = results.rows.item(0).jd;
			         _this.wd = results.rows.item(0).wd;
			        _this.fammerid = results.rows.item(0).fammerid
			        _this.fammername = results.rows.item(0).fammername
			          _this.level = results.rows.item(0).level
			          _this.scale = results.rows.item(0).scale
			          _this.output = results.rows.item(0).output
			          
			          _this.ycdate = results.rows.item(0).date
			          _this.bcdate = results.rows.item(0).date
			          _this.returndate = results.rows.item(0).date
			          
			         document.getElementById('showLevelPicker').value = results.rows.item(0).levelname
			        if( _this.formtype == 0){
			        	_this.acqplantid = results.rows.item(0).type
			        	document.getElementById('plantPicker').value = results.rows.item(0).typename
			        }else{
			        	_this.acqbreedid= results.rows.item(0).type
			        	document.getElementById('breedPicker').value = results.rows.item(0).typename
			        }
			  
   			}, null);
});
			
		},
		switchFormType:function(num){
			this.formtype = num
		},
		getGPS: function() {

			var _this = this
			//自动获取经纬度
			plus.geolocation.getCurrentPosition(function(p) {
				_this.wd = p.coords.latitude
				_this.jd = p.coords.longitude
				console.log(_this.wd)
			}, function(e) {
				alert('获取gps定位失败: ' + e.message);
			});
			setTimeout(function() {
				plus.nativeUI.closeWaiting()
			}, 100);
		},
		savelocal: function() {
			//表单信息验证
			if(this.fammerid.length <= 0) {
				mui.alert("请选择农户信息")
				return
			}
			if(this.level.length <= 0) {
				mui.alert("请选择产品等级")
				return
			}
			if(this.formtype == 1 && this.acqbreedid.length <= 0) {
				mui.alert("请选择养殖品类")
				return
			}
			if(this.formtype == 0 && this.acqplantid.length <= 0) {
				mui.alert("请选择种植品类")
				return
			}
			if(this.scale.length <= 0) {
				mui.alert("请填写产品规模")
				return
			}
			if(this.output.length <= 0) {
				mui.alert("请填写预计产出")
				return
			}
	
			if(this.photos.length <= 0) {
				mui.alert("请添加照片")
				return
			}

			//图片本地缓存
			var _this = this
			db.transaction(function(tx) {
				tx.executeSql('CREATE TABLE IF NOT EXISTS info (id,jd,wd,formtype,fammerid,fammername,type,typename,level,levelname,scale,output,date,localurl,path,des)');
				tx.executeSql('SELECT * FROM info', [], function(tx, results) {
					var len = results.rows.length;
					var fammername = _this.fammername;
					var type = _this.formtype == 0 ? _this.acqplantid : _this.acqbreedid;
					var typename = _this.formtype == 0 ? document.getElementById('plantPicker').value : document.getElementById('breedPicker').value;
					var level = _this.level;
					var levelname = document.getElementById('showLevelPicker').value;
					var scale = _this.scale;
					var output = _this.output;
					var date = _this.returndate;
					var jd = _this.jd;
					var wd = _this.wd;

					if(len == null) {
						len = 0
					}
					//循环遍历图片数组存储
					for(var i = 0; i < _this.photos.length; i++) {
						tx.executeSql('INSERT INTO info (id,jd,wd,formtype,fammerid,fammername,type,typename,level,levelname,scale,output,date,localurl,path,des) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', [len + 1, jd, wd, _this.formtype, _this.fammerid, fammername, type, typename, level, levelname, scale, output, date, _this.photos[i].localurl, _this.photos[i].path,_this.des]);
					}

				}, null);
			});
			mui.alert("已将表单放入待提交列表",function(){
				mui.back()
			})
			

		},
		submitcheck:function(){
			var btn = ["取消","确定"];
			var _this = this
			mui.confirm('是否确认上传？', '提示', btn, function(e) {
				console.log(e.index);
				if(e.index == 1) {
					_this.submit()
				}
			});
		},
		submit: function() {
			console.log("进入提交")
			//表单信息验证

			if(this.fammerid.length <= 0) {
				mui.alert("请选择农户信息")
				return
			}
			if(this.level.length <= 0) {
				mui.alert("请选择产品等级")
				return
			}
			if(this.formtype == 1 && this.acqbreedid.length <= 0) {
				mui.alert("请选择养殖品类")
				return
			}
			if(this.formtype == 0 && this.acqplantid.length <= 0) {
				mui.alert("请选择种植品类")
				return
			}
			if(this.scale.length <= 0) {
				mui.alert("请填写产品规模")
				return
			}
			if(this.output.length <= 0) {
				mui.alert("请填写预计产出")
				return
			}
			if(this.formtype == 1 && this.returndate.length <= 0) {
				mui.alert("请选择预计产出日期")
				return
			}
			if(this.formtype == 0 && this.ycdate.length <= 0) {
				mui.alert("请选择预采日期")
				return
			}
			if(this.formtype == 0 && this.bcdate.length <= 0) {
				mui.alert("请选择必采日期")
				return
			}
			if(this.photos.length <= 0) {
				mui.alert("请添加照片")
				return
			}

			if(this.wd.length <= 0 || this.jd.length <= 0) {
				mui.alert("获取gps定位失败,请刷新后重试")
				return
			}
	
			plus.nativeUI.showWaiting();
			var route = '';
			var type = '';
			var temp = this.formtype == 0 ? this.acqplantid : this.acqbreedid
			for(var i = 0; i < this.photos.length; i++) {
				if(i == 0) {
					route = this.photos[i].path
				} else {

					route = route + "," + this.photos[i].path
				}

			}
			for(var i = 0; i < temp.length; i++) {
				if(i == 0) {
					type = temp[i]
				} else {

					type = type + "," + temp[i]
				}

			}
			var _this = this

			var url = _this.formtype == 0 ? '/savePlant' : '/saveBreed'
			console.log(_this.formtype == 0)
			var param = _this.formtype == 0 ? {
				photo: route,
				createBy: localStorage.localuserid,
				acqFarmerId: _this.fammerid,
				acqPlantId: type,
				scale: _this.scale,
				level: _this.level,
				esOutput: _this.output,
				ycDate: _this.ycdate,
				bcDate: _this.bcdate,
				acqPlantName: document.getElementById('plantPicker').value,
				des: _this.des,
				plantUnit: _this.plantArea,
				returnUnit: _this.returnUnit,
				gps: _this.wd + ',' + _this.jd
			} : {
				photo: route,
				createBy: localStorage.localuserid,
				acqFarmerId: _this.fammerid,
				acqBreedId: type,
				scale: _this.scale,
				level: _this.level,
				esOutput: _this.output,
				esReturnDate: _this.returndate,
				acqBreedName: document.getElementById('breedPicker').value,
				des: _this.des,
				returnUnit: _this.returnUnit,
				gps: _this.wd + ',' + _this.jd
			}
			axios({
				url: sever + url,
				method: 'POST',

				params: param,
				timeout: 50000,

				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				}
			}).then(function(res) {
				if(res.data.success) {

					for(var i = 0; i < _this.photos.length; i++) {
						_this.upload(_this.photos[i].path);
					}

				} else {
					mui.toast("请求出错，请稍后再试");
				}
			})
		},
		upload: function(file) {
			var _this = this
			var uploadurl = _this.formtype == 0 ? '/uploadPlant' : '/uploadBreed'
			var task = plus.uploader.createUpload(sever + uploadurl, {
					method: "POST",
					blocksize: 204800,
					priority: 100
				},
				function(t, status) {
					// 上传完成
					if(status == 200) {
						_this.uploadcount = _this.uploadcount + 1
					} else {
						plus.nativeUI.closeWaiting();
						mui.alert("上传文件出现问题");
					}
				}
			);
			task.addFile(file, {
				key: file
			});

			task.start()
		},
		//选择获取照片方式
		choosePhoto: function() {
			var bts = [{
					title: "拍照"
				}
				/*, {
								title: "从相册选择"
							}*/
			];
			var _this = this;
			plus.nativeUI.actionSheet({
					cancel: "取消",
					buttons: bts
				},
				function(e) {
					if(e.index == 1) {
						_this.getImage();
					} else if(e.index == 2) {
						_this.galleryImgs();
					}
				}
			);
		},
		getImage: function() {
			var newUrlAfterCompress = '';
			var dstname = '';
			var cmr = plus.camera.getCamera();
			var _this = this;
			cmr.captureImage(function(p) {
				plus.io.resolveLocalFileSystemURL(p, function(entry) {
					var localurl = entry.toLocalURL(); //   
					dstname = "_downloads/" + _this.getUid() + ".jpg"; //设置压缩后图片的路径   
					newUrlAfterCompress = _this.compressImage(localurl, dstname);

					_this.photos.push({
						"localurl": localurl,
						"path": dstname,
						"uploaded": false
					});

				});
			});
		},
		galleryImgs: function() { // 从相册中选择图片   
			var _this = this;
			plus.gallery.pick(function(e) {
				var had = _this.photos.length
				for(var i = 0; i < e.files.length; i++) {
					if(i + had < 8) {
						var dstname = "_downloads/" + _this.getUid() + ".jpg"; //设置压缩后图片的路径   
						_this.compressImage(e.files[i], dstname);

						_this.photos.push({
							"localurl": e.files[i],
							"path": dstname,
							"uploaded": false
						});

					}
				}
			}, function(e) {
				console.log("取消选择图片");
			}, {
				filter: "image",
				multiple: true
			});
		},
		getUid: function() {
			return Math.floor(Math.random() * 100000000 + 10000000).toString();
		},
		compressImage: function(src, dstname) {
			plus.zip.compressImage({
					src: src,
					dst: dstname,
					overwrite: true,
					quality: 20
				},
				function(event) {
					return event.target;
				},
				function(error) {
					console.log(error);
					return src;
				}

			);
		},
		delphoto: function(index) {
			this.photos.splice(index, 1);
			this.delNo = (this.delNo - 1) < 0 ? 0 : (this.delNo - 1)
		},

	},
});